from pymysql import connect
from config import *

class Db(object):
    #连接数据库
    def __init__(self):
        self.conn = connect(
            host=DB_HOST,
            port=DB_PORT,
            database=DB_NAME,
            user=DB_USER,
            password=DB_PASS,
            #charset='utf-8'
        )
        self.cursor = self.conn.cursor()

    #以字典形式返回搜索结果
    def get_one(self,sql):
        self.cursor.execute(sql)
        query_result = self.cursor.fetchone()
        if not query_result:
            return None
        fileds = [filed[0] for filed in self.cursor.description]
        return_data = dict()
        for filed,value in zip(fileds,query_result):
            return_data[filed] = value
        return return_data
    #关闭数据库
    def close(self):
        self.cursor.close()
        self.conn.close()


def test():
    db = Db()
    res = db.get_one('select * from users')
    print(res)